package com.codeyang.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.codeyang.domain.Basket;
import com.codeyang.dto.CartMoney;
import com.codeyang.dto.ShopCartResult;
import com.codeyang.service.BasketService;
import com.codeyang.util.LoadUserInfoUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述:
 *
 * @author CodeYang_Site
 * @version 2021/5/31 11:47
 */
@Api(tags = "购物车接口管理")
@RestController
@RequestMapping("p/shopCart")
public class CartController {

    @Autowired
    private BasketService basketService;

    @GetMapping("prodCount")
    @ApiOperation("查询用户购物车数量")
    public ResponseEntity<Integer> getCartCount() {
        String userId = LoadUserInfoUtil.getUserId();
        Integer count = basketService.findCartCount(userId);
        return ResponseEntity.ok(count);
    }


    @PostMapping("changeItem")
    @ApiOperation("修改购物车商品数量")
    public ResponseEntity<Void> changeItem(@RequestBody Basket basket) {
        String userId = LoadUserInfoUtil.getUserId();
        basket.setUserId(userId);
        basketService.changeCartItem(basket);
        return ResponseEntity.ok().build();
    }

    @GetMapping("info")
    @ApiOperation("回显购物车")
    public ResponseEntity<List<ShopCartResult>> info() {
        String userId = LoadUserInfoUtil.getUserId();
        List<ShopCartResult> results = basketService.findCartInfoByUser(userId);
        return ResponseEntity.ok(results);
    }


    @DeleteMapping("deleteItem")
    @ApiOperation("根据购物车条目id删除购物车商品数据")
    public ResponseEntity<Void> deleteItem(@RequestBody List<Long> ids) {
        basketService.removeByIds(ids);
        return ResponseEntity.ok().build();
    }

    @PostMapping("totalPay")
    @ApiOperation("根据购物车条目id计算总付费")
    public ResponseEntity<CartMoney> totalPay(@RequestBody List<Long> basketIds) {
        CartMoney cartMoney = basketService.calculateCartMoney(basketIds);
        return ResponseEntity.ok(cartMoney);
    }

    //---- 远程调用 -----


    @PostMapping("getBasketsByIds")
    @ApiOperation("远程调用购物车拿到购物车集合")
    List<Basket> getBasketsByIds(@RequestBody List<Long> basketIds) {
        return basketService.listByIds(basketIds);
    }


    /**
     * 远程调用清空购物车
     * post请求只能放一个对象在body 注解不可以帮我们合并数据
     *
     * @return
     */
    @PostMapping("clearCart")
    public void clearCart(@RequestParam String userId, @RequestBody ArrayList<Long> skuIds) {
        boolean remove = basketService.remove(new LambdaQueryWrapper<Basket>()
                .eq(Basket::getUserId, userId)
                .in(Basket::getSkuId, skuIds)
        );
    }


}
